<!-- 用于显示1个栏目中的文章表格，进行分页显示，可以显示栏目中的全部文章列表 -->
<template>
  <div class="cms-category-container">
    <!-- 栏目中的文章列表为空，仅显示栏目名称，无文章列表，也不需要显示更多 -->
    <a-list
      size="small"
      :bordered="false"
      :split="false"
      v-if="
        categoryPageArticles === undefined ||
        categoryPageArticles === null ||
        categoryPageArticles.length < 0x1
      "
    >
      <template #header>
        <div class="category-title">
          <div class="category-title-prefix">
            <img v-if="projectCode === 'yzh'" class="img-yzh" />
            <img v-else-if="projectCode === 'ky'" class="img-ky" />
            <img v-else class="img-qc" />
          </div>
          <div class="category-title-text" style="font-family: Microsoft YaHei">{{
            category.name
          }}</div>
        </div>
        <div style="height: 1px; width: 100%">
          <a-divider style="border-color: #ccc; height: 1px" />
        </div>
      </template>
    </a-list>

    <!-- 栏目中的存在文章列表，显示文章列表 -->
    <a-list
      size="small"
      :bordered="false"
      :split="false"
      :data-source="categoryPageArticles"
      v-else
    >
      <template #renderItem="{ item }">
        <a-list-item class="category-article-row">
          <div class="flexBox">
            <!-- 引导符 -->
            <span
              class="category-article-prefix"
              v-if="articleTitlePrefix >= 0x1 && articleTitlePrefix <= 0xc"
            >
              <caret-right-outlined v-show="articleTitlePrefix === 1" />
              <span v-if="articleTitlePrefix === 2">·</span>
              <span v-if="articleTitlePrefix === 3">◦</span>
              <span v-if="articleTitlePrefix === 4">●</span>
              <span v-if="articleTitlePrefix === 5">○</span>
              <span v-if="articleTitlePrefix === 6">✦</span>
              <span v-if="articleTitlePrefix === 7">✧</span>
              <span v-if="articleTitlePrefix === 8">▪</span>
              <span v-if="articleTitlePrefix === 9">▫</span>
              <span v-if="articleTitlePrefix === 10">□</span>
              <span v-if="articleTitlePrefix === 11">★</span>
              <span v-if="articleTitlePrefix === 12">☆</span>
            </span>
            <!-- 文章标题列表 -->
            <!-- 文章标题需要控制的样式有：是否能点击、字体大小、是否置顶显示、显示的字数-->
            <!-- 分为可点击和不可点击，其他样式控制相同 -->
            <span
              v-if="canClick === true"
              class="category-article-title"
              :style="{
                color: (item.tags & 0x8) === 0x8 ? articleTopColor : articleTitleColor,
                fontSize: titleFontSize,
                lineHeight: lineHeight,
                fontFamily: 'Microsoft YaHei',
              }"
              @click="onClickArticleTitle(item)"
            >
              <!-- 在单个栏目的文章列表表格中，整个屏幕只显示当前栏目文章列表，不需要控制显示标题文字的数量，全部显示 -->
              {{ item.title }}
            </span>
            <span
              v-else
              class="category-article-title"
              :style="{
                color: (item.tags & 0x8) === 0x8 ? articleTopColor : articleTitleColor,
                fontSize: titleFontSize,
                lineHeight: lineHeight,
                fontFamily: 'Microsoft YaHei',
              }"
            >
              {{ item.title }}
            </span>
            <!-- 附件下载图标组件 -->
            <span :style="{ width: '20%' }">
              <CmsArticleFilesIconDown
                :key="item.id"
                v-if="!!item.attachment && item.attachment.length > 0x0"
                :values="item.attachment"
              />
            </span>

            <!-- 日期是否显示 -->
            <span v-if="showDate" class="category-article-time">{{
              item.intm != null && item.intm.length > 10 ? item.intm.slice(0, 10) : item.intm
            }}</span>
          </div>
        </a-list-item>
      </template>
      <template #header>
        <div class="category-title">
          <div class="category-title-prefix">
            <img v-if="projectCode === 'yzh'" class="img-yzh" />
            <img v-else-if="projectCode === 'ky'" class="img-ky" />
            <img v-else class="img-qc" />
          </div>
          <div class="category-title-text" style="font-family: 'Microsoft YaHei'">{{
            category.name
          }}</div>
          <!-- 是否显示更多，单个栏目中文章列表为栏目的全部文章，采用分页显示，不再需要显示更多 -->
          <!-- <div
            v-if="showMore"
            class="category-title-more"
            @click="onClickLoadMoreArticles(category)"
            >更多>></div
          > -->
        </div>
        <div style="height: 1px; width: 100%">
          <a-divider style="border-color: #ccc; height: 1px" />
        </div>
      </template>
    </a-list>
    <!-- 文章分页组件 -->
    <div style="height: 1px; width: 100%; padding-bottom: 5px">
      <a-divider style="border-color: #ccc; height: 1px" />
    </div>
    <a-pagination
      v-model:current="currentArticlePage"
      show-quick-jumper
      :showSizeChanger="true"
      :show-total="(total, range) => `共有 ${total} 篇文章`"
      :total="articleTotalCount"
      :pageSize="articlePageSize"
      @change="onArticlePageChange"
      @showSizeChange="onArticlePageSizeChange"
    />
  </div>
</template>
<script lang="ts">
  import { defineComponent, computed, ref } from 'vue';
  import { CaretRightOutlined } from '@ant-design/icons-vue';

  import { CategoryDto } from '/@/api/cms/model/categoryModel';
  import { ArticleQueryConditionDto } from '/@/api/cms/model/articleModel';
  import { queryArticles } from '/@/api/cms/display';
  import { viewArticle } from '/@/api/cms/article';

  import { useGo } from '/@/hooks/web/usePage';
  import { useCmsStore } from '/@/store/modules/cms';
  import { useRouter } from 'vue-router';

  import CmsArticleFilesIconDown from './CmsAticleFilesIconDown.vue';

  import { useGlobSetting } from '/@/hooks/setting';

  export default defineComponent({
    name: 'CmsCategoryArticleTable',
    components: {
      CaretRightOutlined,
      CmsArticleFilesIconDown,
    },
    props: {
      category: {},
      articles: {},
    },
    setup(props) {
      console.log('CmsCategoryArticles.vue get props ', props);
      const go = useGo();
      //使用store必须在setup中，否则会报错
      const cmsStore = useCmsStore();
      const router = useRouter();

      const { globalProjectCode } = useGlobSetting();
      const projectCode = ref<String>(globalProjectCode);

      //当前栏目信息
      const currentCategory = ref<CategoryDto>();
      //文章分页参数
      const currentArticlePage = ref<number>(1);
      const articleTotalCount = ref<number>(10);
      const articlePageSize = ref<number>(10);
      //当前栏目当前分页的文章数据
      const categoryPageArticles = ref([]);

      //定义获取文章显示配置，用于显示该栏目中的文章列表
      //文章列表之间的行高，默认为1.5rem
      let lineHeight = computed(() => {
        if (!!props.category) {
          if (!!props.category.article) {
            let articleJsonString = props.category.article;
            let articleJson = articleJsonString ? JSON.parse(articleJsonString) : {};
            if (!!articleJson) {
              let lineHeight = articleJson.lineHeight;
              console.log('行高', lineHeight);
              if (!!lineHeight && lineHeight > 0) return lineHeight + 'rem';
            }
          }
        }
        return '1.5rem';
      });

      //是否显示更多按钮或文字，默认为显示
      let showMore = computed(() => {
        if (!!props.category) {
          if (!!props.category.article) {
            let articleJsonString = props.category.article;
            let articleJson = articleJsonString ? JSON.parse(articleJsonString) : {};
            if (!!articleJson) {
              let showMore = articleJson.showMore;
              if (!showMore && showMore === false) return false;
            }
          }
        }
        return true;
      });

      //文章标题前导符，默认为1
      let articleTitlePrefix = computed(() => {
        if (!!props.category) {
          if (!!props.category.article) {
            let articleJsonString = props.category.article;
            let articleJson = articleJsonString ? JSON.parse(articleJsonString) : {};
            if (!!articleJson) {
              let prefix = articleJson.prefix;
              if (prefix != undefined && prefix != null) return prefix;
            }
          }
        }
        return 0x1;
      });

      //是否显示发文日期，默认为显示
      let showDate = computed(() => {
        if (!!props.category) {
          if (!!props.category.article) {
            let articleJsonString = props.category.article;
            let articleJson = articleJsonString ? JSON.parse(articleJsonString) : {};
            if (!!articleJson) {
              let showDate = articleJson.showDate;
              if (showDate != undefined && showDate != null && showDate == false) return false;
            }
          }
        }
        return true;
      });

      //文章是否能点击，默认为显示
      let canClick = computed(() => {
        if (!!props.category) {
          if (!!props.category.article) {
            let articleJsonString = props.category.article;
            let articleJson = articleJsonString ? JSON.parse(articleJsonString) : {};
            if (!!articleJson) {
              let canClick = articleJson.canClick;
              if (canClick != undefined && canClick != null && canClick == false) return false;
            }
          }
        }
        return true;
      });

      //文章标题颜色，正常情况下（无标签），默认为黑色
      let articleTitleColor = computed(() => {
        if (!!props.category) {
          if (!!props.category.article) {
            let articleJsonString = props.category.article;
            let articleJson = articleJsonString ? JSON.parse(articleJsonString) : {};
            if (!!articleJson) {
              let titleColor = articleJson.titleColor;
              if (titleColor != undefined && titleColor != null) return titleColor;
            }
          }
        }
        return '#000000';
      });

      //文章标题颜色，有置顶标签时，默认为红色
      let articleTopColor = computed(() => {
        if (!!props.category) {
          if (!!props.category.article) {
            let articleJsonString = props.category.article;
            let articleJson = articleJsonString ? JSON.parse(articleJsonString) : {};
            if (!!articleJson) {
              let topColor = articleJson.topColor;
              if (topColor != undefined && topColor != null) return topColor;
            }
          }
        }
        return '#ff0000';
      });

      //文章标题显示字数，默认显示15个
      let titleDisplayCount = computed(() => {
        if (!!props.category) {
          if (!!props.category.article) {
            let articleJsonString = props.category.article;
            let articleJson = articleJsonString ? JSON.parse(articleJsonString) : {};
            if (!!articleJson) {
              let titleCount = articleJson.displayCount;
              if (titleCount != undefined && titleCount != null) return titleCount;
            }
          }
        }
        return 15;
      });

      //文章标题显示字号，默认显示:medium，取值有smaller,small,medium,large,larger
      let titleFontSize = computed(() => {
        if (!!props.category) {
          if (!!props.category.article) {
            let articleJsonString = props.category.article;
            let articleJson = articleJsonString ? JSON.parse(articleJsonString) : {};
            if (!!articleJson) {
              let fontSize = articleJson.fontSize;
              if (fontSize != undefined && fontSize != null) return fontSize;
            }
          }
        }
        return 'medium';
      });

      //点击文章标题是否打开新的浏览器窗口，默认true打开
      let openNewWindow = computed(() => {
        if (!!props.category) {
          if (!!props.category.article) {
            let articleJsonString = props.category.article;
            let articleJson = articleJsonString ? JSON.parse(articleJsonString) : {};
            if (!!articleJson) {
              let newWindow = articleJson.openNewWindow;
              if (newWindow != undefined && newWindow != null && newWindow == false) return false;
            }
          }
        }
        return true;
      });

      /**
       * 点击文章标题事件，根据文章内容类型进行不同处理；文章类型为超链接时打开新窗口，为其他类型时跳转至文章查看页面
       * @param article 文章信息
       */
      function onClickArticleTitle(article) {
        // console.log('onClickArticleTitle', article);
        if (!article) {
          //文章信息为空无法进行后继处理
        } else {
          if (article.ctype === 3 || article.ctype === '3') {
            //文章内容类型为超链接，打开新窗口
            viewArticle({ id: article.id }).then((res) => {
              window.open(res.content);
            });
          } else {
            if (openNewWindow.value) {
              //打开一个新的浏览器窗口
              const url = router.resolve({
                path: '/cms/article/' + article.id,
              });
              window.open(url.href);
            } else {
              // 在当前浏览器窗口打开
              //使用store存储跳转路由需传递的数据
              cmsStore.setCmsRouteParam({
                isArticle: true,
                id: article.id,
                data: article,
              });
              go('/cms/article/' + article.id);
            }
          }
        }
      }

      /**
       * 查询指定栏目的分页文章信息
       */
      function queryCategoryArticles() {
        console.log(
          'queryCategoryArticles currentCategoryId=' +
            currentCategory.value.id +
            ' currentArticlePage=' +
            currentArticlePage.value +
            ' articlePageSize=' +
            articlePageSize.value,
        );
        //构造查询条件：指定栏目ID、分页、每页条数
        let queryConditionDto: ArticleQueryConditionDto = {
          cid: currentCategory.value.id,
          page: currentArticlePage.value,
          pageSize: articlePageSize.value,
        };
        queryArticles(queryConditionDto)
          .then((res) => {
            console.log('queryArticles res', res);
            //获取后台接口返回结果中的记录总数和当前页的文章列表
            articleTotalCount.value = res.total;
            categoryPageArticles.value = res.items;
          })
          .catch((ex) => {
            console.log('queryArticles ex', ex);
          });
      }

      /**
       * 文章分页点击事件，切换显示第n页文章
       * @param pageNumber
       */
      function onArticlePageChange(pageNumber: number) {
        // console.log('onArticlePageChange pageNumber=' + pageNumber);
        // console.log('onArticlePageChange currentArticlePage=' + currentArticlePage.value);
        //判断分页是否变化，如果变化进行赋值，调用后台接口查询数据
        if (pageNumber != currentArticlePage.value) {
          //实测发现在组件中绑定当前页后对应的变量值已经实时发生改变，在此判断时2个值相等
          //此判断永远不会为true
          console.log('onArticlePageChange pageNumber2=' + pageNumber);
          currentArticlePage.value = pageNumber;
          queryCategoryArticles();
        }
        //不需要判断2个值是否相等，直接调用查询方法；
        queryCategoryArticles();
      }

      /**
       * 文章分页每页数量切换事件
       * @param pageNumber
       */
      function onArticlePageSizeChange(current, size) {
        console.log('onArticlePageSizeChange current=' + current + ' size=' + size);
        articlePageSize.value = size;
        queryCategoryArticles();
      }

      return {
        currentCategory,
        currentArticlePage,
        articleTotalCount,
        articlePageSize,
        categoryPageArticles,
        lineHeight,
        showMore,
        articleTitlePrefix,
        showDate,
        canClick,
        articleTitleColor,
        articleTopColor,
        titleDisplayCount,
        titleFontSize,
        openNewWindow,
        queryCategoryArticles,
        onClickArticleTitle,
        onArticlePageChange,
        onArticlePageSizeChange,
        projectCode,
      };
    },
    watch: {
      //接收props传值由于无法确定是否完成传值和接收，因此在watch中进行处理，props传值完成或变化后再对当前的数据进行更新并调用方法对页面显示进行更新
      category: function (newVal, oldVal) {
        console.log('watch props category', newVal);
        this.currentCategory = newVal;
        this.queryCategoryArticles();
      },
      articles: function (newVal, oldVal) {
        console.log('watch props articles', newVal);
        this.categoryPageArticles = newVal;
      },
    },
  });
</script>
<style scoped lang="less">
  @import './cms.less';

  //覆盖antd的默认样式，解决头部高度过大的问题
  .ant-list:deep(.ant-list-header) {
    // line-height: 1;
    padding-bottom: 0px;
  }

  .cms-category-container > div {
    height: calc(100% - 4rem); //下方的分页高度
  }

  .category-title-text {
    font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode',
      Geneva, Verdana, sans-serif;
  }
</style>
